<template>
  <div class="common-choose-dialog-wrap">
    <span
      class="label"
      @click="showDialog"
      v-if="!selectNames.length"
      :style="{ '--theme-color': systemInfo.theme }"
      data-test="alarm-code-button-dialog"
      >请选择</span
    >

    <div class="name-list" v-else @click="showDialog">
      <el-tag
        type="success"
        v-for="(item, index) in selectNames"
        :key="index"
        closable
        @close="delUser(index)"
      >
        {{ item }}
      </el-tag>
      <el-tag type="success" v-if="tempData.length > 3"
        >+{{ tempData.length - 3 }}</el-tag
      >
    </div>

    <common-choose-dialog
      ref="ChooseDialog"
      multiple
      :max="max"
      title="人员"
      @submitForm="submitForm"
    >
      <!--tab标签页-->
      <common-tabs slot="tabs" v-model="activeName" @tab-click="changeTabs">
        <el-tab-pane label="全部列表" name="unselected"></el-tab-pane>
        <el-tab-pane label="已选择列表" name="selected"></el-tab-pane>
      </common-tabs>
      <!--全部列表-->
      <template v-if="activeName === 'unselected'">
        <common-tree
          slot="tree"
          v-loading="treeLoading"
          :isRequest="isRequest"
          :treeData="treeData"
          :treeProp="treeProp"
          :current-node-key="currentNodeKey"
          :isShowFilter="false"
          is-slot
          @handleNodeClick="handleNodeClick"
        >
          <div
            style="width: 100%"
            slot-scope="{ scope }"
            :class="{ 'e-t-content': !scope.data.freeze }"
          >
            <common-carousel-text
              :content="scope.node.label"
              :index="scope.node.id"
              :font-size="14"
            >
            </common-carousel-text>
          </div>
        </common-tree>

        <common-search slot="search" @search="handleQuery" @reset="resetQuery">
          <el-form
            @submit.native.prevent
            :model="queryForm"
            ref="queryForm"
            :inline="true"
            label-width="50px"
          >
            <el-form-item label="用户名">
              <common-input
                v-model="queryForm.userName"
                clearable
                @enter="handleQuery"
              />
            </el-form-item>
          </el-form>
        </common-search>

        <common-table
          v-loading="listLoading"
          slot="content"
          ref="unSelectList"
          :data="allList"
          isSetRowKey
          :row-key="'userId'"
          @select="selectionRow"
          @selection-change="handleSelectionChange"
          data-test="alarm-code-choose-dialog-table"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
            :reserve-selection="true"
            data-test="alarm-code-choose-dialog-selection"
          >
          </el-table-column>
          <el-table-column label="用户名" align="left" prop="userName" />
          <el-table-column label="姓名" align="left" prop="nickName" />
          <el-table-column label="手机号" align="left" prop="phone" />
        </common-table>

        <pagination
          slot="pagination"
          v-show="total > 0"
          :total="total"
          :page.sync="queryForm.pageNum"
          :limit.sync="queryForm.pageSize"
          @pagination="handleList"
        />
      </template>

      <!--已选择-->
      <template v-else>
        <div slot="button">
          <el-button
            type="danger"
            icon="el-icon-delete"
            plain
            :disabled="!selectedDeleteValue.length"
            @click="handleDelete"
            >批量删除
          </el-button>
          <span style="margin-left: 24px"
            >总数量：{{ selectedData.length }}人</span
          >
        </div>

        <common-table
          slot="content"
          v-loading="selectListLoading"
          ref="selectList"
          :data="selectedData"
          @selection-change="handleSelectForDel"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="用户名" align="left" prop="userName" />
          <el-table-column label="姓名" align="left" prop="nickName" />
          <el-table-column label="手机号" align="left" prop="phone" />
          <el-table-column label="操作" align="left" width="50">
            <template slot-scope="scope">
              <el-button type="text" @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </common-table>
      </template>
    </common-choose-dialog>
  </div>
</template>

<script>
import HandleChooseDialog from "@/mixins/modules/HandleChooseDialog";
import { user_list, dept_select } from "@/api/management/usercenter/user.js";
import { getSelectedNoticeUsers } from "@/api/system/alarmCode";
import { decode, encode } from "@/utils/aesUtils";
import Utils, { _deepClone } from "@/utils";
import { mapGetters } from "vuex";

export default {
  name: "chooseDialog",
  mixins: [HandleChooseDialog],
  props: {
    id: {
      type: [Number, String],
    },
  },
  data() {
    return {
      activeName: "unselected",
      treeLoading: false,
      treeData: [],
      treeProp: {},
      allList: [],
      currentNodeKey: "",
      queryForm: {
        deptId: "",
        userName: "",
        status: "0",
        pageNum: 1,
        pageSize: 10,
      },
      selectListLoading: false, //已选择列表loading
      selectedData: [], //已选择列表
      selectedDeleteValue: "", //已选择列表中选中的数据
      selectNames: [], //用于展示选择人员名称
      tempData: [],
      key: "userId",
      max: 10,
    };
  },
  computed: {
    ...mapGetters(["systemInfo"]),
  },
  watch: {
    id: {
      handler: function (val) {
        if (val && !this.selectedData.length) {
          this.handleSelectedList();
        }
      },
    },
    tempData: {
      handler: function (val) {
        this.setSelectNames();
      },
      deep: true,
    },
    allList: {
      handler: function (val) {
        if (val.length) {
          this.changeTabs();
        }
      },
      deep: true,
    },
    selectedData: {
      handler: function (val) {
        if (val.length) {
          this.changeTabs();
        }
      },
      deep: true,
    },
  },
  methods: {
    showDialog() {
      this.$refs.ChooseDialog.show();
      this.selectedData = _deepClone(this.tempData);
      this.queryForm = {
        deptId: "",
        userName: "",
        status: "0",
        pageNum: 1,
        pageSize: 10,
      };
      this.handleList();
      this.handleTreeList();
      // this.changeTabs()
    },
    //切换分页
    changeTabs() {
      if (this.activeName === "unselected") {
        this.changeRowSelection();
      }
    },
    //树节点点击赋值查询项
    setQueryForNode(info) {
      this.queryForm.userName = "";
      this.queryForm.deptId = info.data.id || info.data.key || info.data.value;
    },
    //弹窗提交事件
    submit() {
      if (this.selectedData.length > 10) {
        this.isClosed = false;
        return this.$GlobalErrorConfirm(
          "添加失败",
          `最多只能选择${this.max}个人员！`
        );
      } else {
        this.isClosed = true;
        this.tempData = _deepClone(this.selectedData);
        this.$emit("getSelectData", this.tempData);
      }
    },
    //展示选中用户姓名
    setSelectNames() {
      if (this.tempData.length) {
        this.selectNames =
          this.tempData.length > 2
            ? this.tempData.map((item) => item.nickName).slice(0, 3)
            : this.tempData.map((item) => item.nickName);
      } else {
        this.selectNames = [];
      }
    },
    //重置筛选条件
    resetForm() {
      this.queryForm.userName = "";
    },
    //展示中删除人员
    delUser(index) {
      this.tempData.splice(index, 1);
      this.$emit("getSelectData", this.tempData);
    },

    /**
     * 获取全部列表
     * @returns {Promise<any>}
     */
    getList() {
      return new Promise((resolve, reject) => {
        user_list(this.queryForm).then((res) => {
          if (res && res.code === 200) {
            let list = res.rows.reduce((r, c) => {
              r.push({
                ...c,
                phone: Utils.phoneEncryption(decode(c.phonenumber)),
                decodeEmail: Utils.emailEncryption(decode(c.email)),
              });
              return r;
            }, []);
            let total = res.total;
            resolve({ list, total });
          } else {
            this.allList = [];
            this.total = 0;
          }
        });
      });
    },
    /**
     * 获取已选择人员列表
     * @returns {Promise<any>}
     */
    getSelectedList() {
      return new Promise((resolve, reject) => {
        let params = {
          id: this.id,
          deptId: "",
          userName: "",
          pageNo: 1,
          pageSize: 10,
        };
        getSelectedNoticeUsers(params).then((res) => {
          if (res && res.code === 200) {
            resolve(res.data);
          } else {
            reject();
          }
        });
      });
    },
    /**
     * 获取树菜单
     * @returns {Promise<any>}
     */
    getTreeList() {
      return new Promise((resolve, reject) => {
        dept_select({}).then((res) => {
          if (res && res.code === 200) {
            resolve(res.data);
          }
        });
      });
    },
  },
  mounted() {},
};
</script>

<style scoped lang="scss">
.common-choose-dialog-wrap {
  .label {
    font-size: 14px;
    color: var(--theme-color);
    cursor: pointer;
  }

  .name-list {
    width: fit-content;

    .el-tag {
      margin-right: 4px;
      cursor: pointer;
    }
  }
}
</style>
